
package com.htd.htdapmservice.task;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htd.htdapmdmo.OneAlertKey;
import com.htd.htdapmservice.service.intf.OneAlertKeyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmcommon.enums.AlarmSendStatus;
import com.htd.htdapmcommon.enums.AlarmsLevelEnum;
import com.htd.htdapmcommon.enums.AlarmsStatusEnum;
import com.htd.htdapmdmo.LogAnalyzeErrorRecord;
import com.htd.htdapmservice.dao.LogAnalyzeErrorRecordDao;
import com.htd.htdapmservice.service.intf.OneAlertService;
import com.taobao.pamirs.schedule.IScheduleTaskDealMulti;
import com.taobao.pamirs.schedule.TaskItemDefine;


@Component("logErrorAlarmTask")
public class LogErrorAlarmTask implements IScheduleTaskDealMulti<LogAnalyzeErrorRecord> {
    private static final Logger logger = LoggerFactory.getLogger(LogErrorAlarmTask.class);

    @Autowired
    private LogAnalyzeErrorRecordDao logAnalyzeErrorRecordDao;

    @Autowired
    private OneAlertService  oneAlertService;

    private OneAlertKeyService oneAlertKeyService;
    /**
     *
     * @param logAnalyzeErrorRecordList
     * @param ownSign
     * @return
     * @throws Exception
     */
    @Override
    public boolean execute(LogAnalyzeErrorRecord[] logAnalyzeErrorRecordList, String ownSign) throws Exception {
        logger.info("LogErrorAlarmTask execute Entrance, itemBrands : {}, ownSign : {}", JSONObject.toJSONString(logAnalyzeErrorRecordList), JSONObject.toJSONString(ownSign));
        boolean result = true;
        try {
            if (logAnalyzeErrorRecordList!=null &&logAnalyzeErrorRecordList.length>0) {
                for (LogAnalyzeErrorRecord logAnalyzeErrorRecord : logAnalyzeErrorRecordList) {
                    AlarmInto alarmInto = new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(logAnalyzeErrorRecord.getProductTypeCode());
                    alarmInto.setAlarmsDetail(logAnalyzeErrorRecord.getAlarmsDetail());
//                    alarmInto.setAlarmsTitle(ProductCategoryEnum.getValueByCode(logAnalyzeErrorRecord.getProductTypeCode())+"日志异常");
                    alarmInto.setAlarmsTitle(oneAlertKeyService.findOneAlertKeyByProductCode(logAnalyzeErrorRecord.getProductTypeCode()).getProductName()+"日志异常");
                    AlarmResult alarmResult = oneAlertService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        logAnalyzeErrorRecord.setSendStatus(AlarmSendStatus.SEND_YES);
                        logAnalyzeErrorRecord.setUpdateTime(new Date());
                        logAnalyzeErrorRecordDao.updateLogAnalyzeErrorRecordById(logAnalyzeErrorRecord);
                    }
                }
            }
        }catch (Exception e) {
            logger.error("LogErrorAlarmTask execute error", e);
            result = false;
        }
        return result;
    }

/**
     * 选择任务数据。
     * @param taskParameter 任务参数
     * @param ownSign 当前环境名称
     * @param taskQueueNum 当前任务类型的任务队列数量
     * @param taskItemList 当前调度服务器，分配到的可处理队列
     * @param eachFetchDataNum 每次获取数据的数量
     * @return
     * @throws Exception
     */

    @Override
    public List<LogAnalyzeErrorRecord> selectTasks(String taskParameter, String ownSign, int taskQueueNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum) throws Exception {
        logger.info("LogErrorAlarmTask selectTasks Entrance, taskParameter : {}, ownSign : {}, taskQueueNum : {}, taskItemList : {}," +
                "eachFetchDataNum : {}", new Object[]{JSONObject.toJSONString(ownSign), JSONObject.toJSONString(taskParameter),
                JSONObject.toJSONString(taskQueueNum), JSONObject.toJSONString(taskItemList), JSONObject.toJSONString(eachFetchDataNum)});
        List<LogAnalyzeErrorRecord> logAnalyzeErrorRecordList = new ArrayList<LogAnalyzeErrorRecord>();
        try{
            List<String> taskIdList = new ArrayList<String>();
            Map<String, Object> paramMap = new HashMap<>();
            if (taskItemList != null && taskItemList.size() > 0) {
                for (TaskItemDefine taskItem : taskItemList) {
                    taskIdList.add(taskItem.getTaskItemId());
                }
                // 根据id和队列数取摩，在taskIdList中则被该任务查询并执行
                paramMap.put("taskQueueNum", taskQueueNum);
                paramMap.put("taskIdList", taskIdList);
                // 默认查询数量
                paramMap.put("rows", eachFetchDataNum > 0 ? eachFetchDataNum : 1000);
                logAnalyzeErrorRecordList = logAnalyzeErrorRecordDao.findLogAnalyzeErrorRecordListByStatus(AlarmSendStatus.SEND_NO.getCode());
            }
        } catch (Exception e){
            logger.error("LogErrorAlarmTask selectTasks error:", e);
        }
        return logAnalyzeErrorRecordList;
    }

    @Override
    public Comparator getComparator() {
        return new Comparator<LogAnalyzeErrorRecord>() {
            public int compare(LogAnalyzeErrorRecord o1, LogAnalyzeErrorRecord o2) {
                Long id1 = o1.getId();
                Long id2 = o2.getId();
                return id1.compareTo(id2);
            }
        };
    }

}


